package com.android.ContactPresets;

import java.io.FileNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ContactsDbAdapter {
	private SQLiteDatabase mDb;
	private final Context mCtx;

	// Constants to access table columns
	public static final String KEY_NAME = "name";
	public static final String KEY_HOME = "home";
	public static final String KEY_MOBILE = "mobile";
	public static final String KEY_PREFIX = "prefix";
	public static final String KEY_EMAIL = "email";
	public static final String KEY_PRESET1 = "preset1";
	//This is a dummy field for possible future use
	public static final String KEY_PRESET2 = "preset2"; 
	public static final String KEY_ROWID = "_id";

	// Constants for DB operations
	private static final String DATABASE_NAME = "data";
	private static final String DATABASE_TABLE = "contacts";
	private static final int DATABASE_VERSION = 2;
	private static final String DATABASE_CREATE = "create table contacts(_id integer primary key autoincrement, "
		+ "name text not null, home text, mobile text, prefix text,  email text, preset1 text, preset2 text);";

	public ContactsDbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	/**
	 * Open the contacts database. If it cannot be opened, try to create a new
	 * instance of the database. If it cannot be created, throw an exception to
	 * signal the failure
	 * 
	 * @return this (self reference, allowing this to be chained in an
	 *         initialization call)
	 * @throws SQLException
	 *             if the database could be neither opened or created
	 */
	public ContactsDbAdapter open() throws SQLException {
		try {
			mDb = mCtx.openDatabase(DATABASE_NAME, null);
		} catch (FileNotFoundException e) {
			try {
				mDb = mCtx.createDatabase(DATABASE_NAME, DATABASE_VERSION, 0,
						null);
				mDb.execSQL(DATABASE_CREATE);
			} catch (FileNotFoundException e1) {
				throw new SQLException("Could not create database");
			}
		}
		return this;
	}

	/**
	 * Closes the DB.
	 */
	public void close() {
		mDb.close();
	}

	/**
	 * Deletes the specified contact.
	 * 
	 * @param rowId
	 *            id of contact to delete
	 * @return true if deleted, false otherwise
	 */
	public boolean deleteContact(long rowId) {
		return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	/**
	 * Updates the contacts table with new values.
	 * 
	 * @param rowId
	 *            id of contact to update
	 * @param name
	 *            name of contact
	 * @param home
	 *            home number of contact
	 * @param mobile
	 *            mobile number of contact to delete
	 * @param prefix
	 *            number to prefix when calling
	 * @param email
	 *            email of contact
	 * @param preset1
	 *            preset line 1
	 * @param preset2
	 *            preset line 2
	 * @return true if updated, false otherwise
	 */
	public boolean updateContact(long rowId, String name, String home,
			String mobile, String prefix, String email, String preset1,
			String preset2) {
		ContentValues args = new ContentValues();
		args.put(KEY_NAME, name);
		args.put(KEY_HOME, home);
		args.put(KEY_MOBILE, mobile);
		args.put(KEY_PREFIX, prefix);
		args.put(KEY_EMAIL, email);
		args.put(KEY_PRESET1, preset1);
		args.put(KEY_PRESET2, preset2);
		return (mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0);

	}

	/**
	 * Fetch a contact from the database
	 * 
	 * @param rowId
	 *            id of contact to fetch
	 * @return Cursor pointing to the fetched row if found.
	 * @throws SQLException
	 *             if rowId is not found.
	 */
	public Cursor fetchContact(long rowId) throws SQLException {
		Cursor result = mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID,
				KEY_NAME, KEY_HOME, KEY_MOBILE, KEY_PREFIX, KEY_EMAIL,
				KEY_PRESET1, KEY_PRESET2 }, KEY_ROWID + "=" + rowId, null,
				null, null, null);
		if (result.count() == 0 || result.first() == false) {
			throw new SQLException("No contact matching ID: " + rowId);
		}
		return result;
	}

	/**
	 * Fetch all contacts from database.
	 * 
	 * @return a Cursor pointing to the fetched rows.
	 */
	public Cursor fetchAllContacts() {
		Cursor result = mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID,
				KEY_NAME, KEY_HOME, KEY_MOBILE, KEY_PREFIX, KEY_EMAIL,
				KEY_PRESET1, KEY_PRESET2 }, null, null, null, null, null);
		return result;
	}

	/**
	 * Returns N contacts starting from startRowId to startRowId + N.
	 * 
	 * @param startRowId
	 * @param numRows
	 * @return a Cursor pointing to the fetched rows.
	 * @throws SQLException
	 */
	public Cursor fetchNContacts(long startRowId, int numRows)	throws SQLException 
	{
		Cursor result = mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID,
				KEY_NAME, KEY_HOME, KEY_MOBILE, KEY_PREFIX, KEY_EMAIL,
				KEY_PRESET1, KEY_PRESET2 }, KEY_ROWID + ">=" + startRowId
				+ " AND " + KEY_ROWID + "<" + (startRowId + numRows), null, null,
				null, null);
		if (result.count() == 0 || result.first() == false) {
			throw new SQLException("No contacts matching ID range");
		}
		return result;
	}


	public Cursor runQuery(String query)		
	{
		Cursor result = mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID,
				KEY_NAME, KEY_HOME, KEY_MOBILE, KEY_PREFIX, KEY_EMAIL,
				KEY_PRESET1, KEY_PRESET2 }, query, null, null,
				null, null);
		return result;
	}
	/**
	 * Creates the contact in the table.
	 * 
	 * @param rowId
	 *            id of contact to create
	 * @param name
	 *            name of contact
	 * @param home
	 *            home number of contact
	 * @param mobile
	 *            mobile number of contact to delete
	 * @param prefix
	 *            number to prefix when calling
	 * @param email
	 *            email of contact
	 * @param preset1
	 *            preset line 1
	 * @param preset2
	 *            preset line 2
	 * @return true if updated, false otherwise
	 */
	public long createContact(String name, String home, String mobile,
			String prefix, String email, String preset1, String preset2) {
		ContentValues args = new ContentValues();
		args.put(KEY_NAME, name);
		args.put(KEY_HOME, home);
		args.put(KEY_MOBILE, mobile);
		args.put(KEY_PREFIX, prefix);
		args.put(KEY_EMAIL, email);
		args.put(KEY_PRESET1, preset1);
		args.put(KEY_PRESET2, preset2);
		return (mDb.insert(DATABASE_TABLE, null, args));

	}
}
